package cc.fs.kotlin.ui.demo

import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.widget.Button
import android.widget.ImageView
import cc.fs.kotlin.R
import cc.fs.kotlin.ui.activity.CropActivity
import cc.fs.kotlin.ui.activity.helper.BaseActivity
import cc.fs.kotlin.utils.ImageUtils
import cc.fs.kotlin.utils.SelectPhotoHelper
import cc.fs.kotlin.utils.bindView

/**
 * 图片选择及剪切操作
 * Created by fostion on 3/1/16.
 */
class ImageSelectDemo: BaseActivity() {

    val btn: Button by bindView(R.id.btn)
    val image: ImageView by bindView(R.id.imageView)
    var selectPhotoHelper:SelectPhotoHelper ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_demo_image_select)

        selectPhotoHelper = SelectPhotoHelper(this@ImageSelectDemo, object : SelectPhotoHelper.OnGetPhotoListener {
            override fun onSuccess(path: String) {
                if (!TextUtils.isEmpty(path)) {
                    CropActivity.start(this@ImageSelectDemo,path)
                } else {
                    showToast("图片获取异常，请重新尝试")
                }
            }

            override fun onFail(status: SelectPhotoHelper.Status?) {
            }
        })
        selectPhotoHelper?.useSource(SelectPhotoHelper.Source.Camera)
        selectPhotoHelper?.useSource(SelectPhotoHelper.Source.PhotoGallery)

        btn.setOnClickListener{
            selectPhotoHelper?.show()
        }
    }

    override fun handler(msg: Message) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(requestCode == CropActivity.FALG_CROP){
            val byteArray = data?.getByteArrayExtra("bitmap")
            if (byteArray != null) {
                image.setImageBitmap(ImageUtils.bytes2Bitmap(byteArray))
            } else {
                showToast("获取头像失败")
            }
        } else {
            selectPhotoHelper?.onActivityResult(requestCode, resultCode, data)
        }
    }
}